<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="站点名称" prop="stationName">
        <el-input v-model="queryParams.stationName" placeholder="请输入站点名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="站点编号" prop="stationId">
        <el-input
          v-model="queryParams.stationId"
          placeholder="请输入站点编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="电桩编号" prop="equipmentCode">
        <el-input
          v-model="queryParams.equipmentCode"
          placeholder="请输入电桩编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="电桩数量/个" prop="pipeNum">
        <el-input
          v-model="queryParams.pipeNum"
          placeholder="请输入电桩数量/个"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="绑定白名单" prop="listName">
        <el-input
          v-model="queryParams.listName"
          placeholder="请输入绑定白名单"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="下发时间" prop="sendTime">
        <el-date-picker
          clearable
          v-model="queryParams.sendTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择下发时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="最后更新时间" prop="lastedUpdateTime">
        <el-date-picker
          clearable
          v-model="queryParams.lastedUpdateTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择最后更新时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="白名单表id" prop="whiteId">
        <el-input
          v-model="queryParams.whiteId"
          placeholder="请输入白名单表id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="电桩VIN码容量" prop="maxVinNumber">
        <el-input
          v-model="queryParams.maxVinNumber"
          placeholder="请输入电桩VIN码容量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['business:vin:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['business:vin:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['business:vin:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['business:vin:export']">导出</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="warning" plain size="mini" @click="toWhite">白名单管理</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="vinList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="站点编号" align="center" prop="stationId" />
      <el-table-column label="站点名称" align="center" prop="stationName" />
      <el-table-column label="电桩数量/个" align="center" prop="stationId">
        <template slot-scope="scope">
          <span>{{ proNum(scope.row.stationId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="绑定白名单" align="center" prop="listName" />
      <el-table-column label="下发时间" align="center" prop="sendTime" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.sendTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最后更新时间" align="center" prop="lastedUpdateTime" width="120">
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.lastedUpdateTime, "{y}-{m}-{d}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="下发状态" align="center" prop="whiteListStatus">
        <template slot-scope="scope">
          <span>{{ scope.row.whiteListStatus == '1' ? '完成' : '未完成' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="250">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="issuingVin(scope.row, 'issuing')"
            v-hasPermi="['business:vin:edit']">下发白名单</el-button>
          <el-button size="mini" type="text" @click="issuingVin(scope.row, 'close')"
            v-hasPermi="['business:vin:edit']">清除白名单</el-button>
          <!-- <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['business:vin:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['business:vin:remove']">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改VIN码白名单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row :gutter="20">
          <el-col :span="12"><el-form-item label="站点编号" prop="stationId">
              <el-input v-model="form.stationId" placeholder="请输入站点编号" /> </el-form-item></el-col>
          <el-col :span="12"><el-form-item label="站点名称" prop="stationName">
              <el-input v-model="form.stationName" placeholder="请输入站点名称" /> </el-form-item></el-col>
          <el-col :span="12"><el-form-item label="电桩编号" prop="equipmentCode">
              <el-input v-model="form.equipmentCode" placeholder="请输入电桩编号" /> </el-form-item></el-col>
          <el-col :span="12"><el-form-item label="电桩数量/个" prop="pipeNum">
              <el-input v-model="form.pipeNum" placeholder="请输入电桩数量/个" /> </el-form-item></el-col>
          <el-col :span="12"><el-form-item label="绑定白名单" prop="whiteId">
              <el-select v-model="form.whiteId" placeholder="请选择白名单" style="width: 100%">
                <el-option v-for="item in whiteList" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select> </el-form-item></el-col>
          <el-col :span="12"><el-form-item label="下发时间" prop="sendTime">
              <el-date-picker style="width: 100%" clearable v-model="form.sendTime" type="date"
                value-format="yyyy-MM-dd" placeholder="请选择下发时间">
              </el-date-picker> </el-form-item></el-col>
          <el-col :span="12"><el-form-item label="最后更新时间" prop="lastedUpdateTime">
              <el-date-picker style="width: 100%" clearable v-model="form.lastedUpdateTime" type="date"
                value-format="yyyy-MM-dd" placeholder="请选择最后更新时间">
              </el-date-picker> </el-form-item></el-col>
          <!-- <el-col :span="12"
            ><el-form-item label="白名单表id" prop="whiteId">
              <el-input
                v-model="form.whiteId"
                placeholder="请输入白名单表id"
              /> </el-form-item
          ></el-col> -->
          <el-col :span="12"><el-form-item label="电桩VIN码容量" prop="maxVinNumber">
              <el-input v-model="form.maxVinNumber" placeholder="请输入电桩VIN码容量" /> </el-form-item></el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="whiteTitle" :visible.sync="dialogTableVisible" center @close="resetIssuingStatus">
      <el-steps style="justify-content: center;" :space="200" :active="issuingActive" finish-status="success"
        align-center>
        <el-step :title="title1">
        </el-step>
        <el-step :title="title2">
        </el-step>
        <el-step :title="title3">
        </el-step>
      </el-steps>
      <div v-show="issuingActive == 1" class="infoBox">
        <div class="serachBox">
          <el-input v-model="staitonVin" :disabled="true" style="width: 200px;"></el-input>
          <el-input v-model="queryParamsOne.equipmentCode" placeholder="电桩编号"
            style="width: 200px;margin: 0 10px;"></el-input>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="oneSearch">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="oneRest">重置</el-button>
        </div>
        <el-table :data="gridData" @selection-change="selectionChangeOne">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column property="equipmentCode" label="电桩编号" width="150"></el-table-column>
          <el-table-column property="power" label="电桩VIN码容量" width="200"></el-table-column>
          <el-table-column property="address" label="白名单名称（数量）"></el-table-column>
          <el-table-column property="address" label="下发状态">
            <template slot-scope="scope">
              {{ scope.row.isOnline == '1' ? '完成' : '未完成' }}
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div v-show="issuingActive == 2" class="infoBox">
        <div class="serachBox">
          <el-input v-model="staitonVin" :disabled="true" style="width: 200px;"></el-input>
          <span v-if="whiteTitle == 'VIN码白名单配置'" style="padding: 0 10px 0 30px;">白名单列表</span>
          <el-select v-if="whiteTitle == 'VIN码白名单配置'" v-model="valueVin" placeholder="请选择" @change="vinChange">
            <el-option v-for="item in whiteList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </div>
        <el-table :data="towList">
          <el-table-column property="equipmentCode" label="电桩编号" width="150"></el-table-column>
          <el-table-column property="power" label="电桩容量" width="200"></el-table-column>
          <el-table-column property="address" label="已绑定白名单名称（数量）"></el-table-column>
          <el-table-column v-if="whiteTitle == 'VIN码白名单配置'" property="whiteName" label="已选择白名单名称（数量）">
            <template slot-scope="scope">
              <div v-if="scope.row.whiteName">
                {{ scope.row.whiteName }}({{ scope.row.listSize }})
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-show="issuingActive == 3" class="infoBox">
        <el-table :data="gridData">
          <el-table-column property="date" label="电桩编号" width="150"></el-table-column>
          <el-table-column property="name" label="电桩容量" width="200"></el-table-column>
          <el-table-column property="address" label="已选择白名单名称（数量）"></el-table-column>
          <el-table-column property="address" label="下发状态"></el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" v-if="issuingActive != 1" @click="previousStep">上一步</el-button>
        <el-button type="primary" v-if="issuingActive != 3" @click="nextStep">下一步</el-button>
        <el-button type="primary" v-if="issuingActive == 3" @click="startIssuing">开始下发</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listVin, getVin, delVin, addVin, updateVin } from "@/api/business/vin";
import { listStake } from "@/api/business/stake";
import {
  listchargeStation,

} from "@/api/business/chargeStation";
import { listWhite } from "@/api/business/white";
import { Message } from "element-ui";
import { computed } from "vue";
export default {
  name: "Vin",

  data() {
    return {
      whiteTitle: '',
      title1: '',
      title2: '',
      title3: '',
      valueVin: null,
      idsOne: [],
      oneCode: null,
      staitonVin: null,
      issuingActive: 1,
      gridData: [],
      dialogTableVisible: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // VIN码白名单表格数据
      vinList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        stationId: null,
        stationName: null,
        equipmentCode: null,
        pipeNum: null,
        listName: null,
        id: null,
        sendTime: null,
        lastedUpdateTime: null,
        whiteListStatus: null,
        sendType: null,
        whiteId: null,
        maxVinNumber: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        whiteId: [
          {
            required: true,
            message: "请绑定白名单",
            trigger: "change",
          },
        ],
      },
      whiteList: [],
      queryParamsOne: {
        pageNum: 1,
        pageSize: 10,
        stationId: null,
        equipmentCode: null,
      },
      stakeList: [],
      towList: []
    };
  },
  created() {
    this.getList();
    this.getlistStake()
  },
  methods: {
    // 重置下发白名单步骤条状态
    resetIssuingStatus() {
      this.issuingActive = 1; // 重置步骤条到第一步
      this.idsOne = []; // 清空选中的电桩
      this.valueVin = null; // 清空选中的白名单
      this.towList = []; // 清空第二步表格数据
      this.queryParamsOne = {
        pageNum: 1,
        pageSize: 10,
        stationId: null,
        equipmentCode: null,
      }
    },
    vinChange() {
      // 1. 找到当前选中的白名单数据（匹配valueVin）
      const selectedWhite = this.whiteList.find(item => item.value === this.valueVin);
      if (!selectedWhite) return; // 若未找到匹配数据，直接返回

      // 2. 给towList每一项添加whiteName（白名单名称）和listSize（数量）
      this.towList = this.towList.map(item => ({
        ...item, // 保留原有电桩数据（如equipmentCode、power等）
        whiteName: selectedWhite.label, // 从选中白名单取名称
        listSize: selectedWhite.listSize // 从选中白名单取数量
      }));
    },
    getlistVin() {
      listVin().then((response) => {
        this.vinList = response.rows
      })
    },
    getlistStake() {
      listStake().then((response) => {
        this.stakeList = response.rows
      })
    },
    proNum(stationId) {
      if (!stationId) return 0; // 若stationId为空，返回0
      // 过滤出stationId匹配的电桩，并返回数量
      return this.stakeList.filter(item => item.stationId === stationId).length;
    },
    selectionChangeOne(selection) {
      this.idsOne = selection;
    },
    oneRest() {
      this.queryParamsOne.equipmentCode = null
      this.getOneList()
    },
    oneSearch() {
      this.getOneList()
    },
    // 下发白名单上一步
    previousStep() {
      this.issuingActive = this.issuingActive - 1
    },
    // 下发白名单下一步
    nextStep() {

      if (this.issuingActive == 2) {
        if (this.valueVin && this.issuingActive == 2) {

          this.issuingActive++
        }
        else {
          this.$message.warning('请选择需要下的发白名单!')

        }
      }
      if (this.issuingActive == 1) {
        if (this.idsOne.length > 0) {
          this.towList = this.idsOne
          this.getListWhite();
          this.issuingActive++
        } else {
          this.$message.warning('请勾选需要下发白名单的电桩!')
        }
      }
    },
    issuingVin(val, type) {
      console.log(val,'sss')
      if (type == 'issuing') {
        this.whiteTitle = 'VIN码白名单配置'
        this.title1 = '选择需要绑定的电桩'
        this.title2 = '选择下发的白名单'
        this.title3 = '点击【开始下发】'
      } else {
        this.whiteTitle = '清除白名单'
        this.title1 = '选择需要清除的电桩'
        this.title2 = '确认清除'
        this.title3 = '点击【确认清除】'
      }
      this.staitonVin = val.stationName
      this.queryParamsOne.stationId = val.stationId
      this.getOneList()
      this.dialogTableVisible = true
    },
    getOneList() {
      listStake(this.queryParamsOne).then((response) => {
        this.gridData = response.rows
      })
    },
    toWhite() {
      this.$router.push("/business/white/index");
    },
    getListWhite() {
      listWhite().then((response) => {
        this.whiteList = response.rows.map((item) => {
          return {
            value: item.id,
            label: item.listName,
            listSize: item.listSize
          };
        });
      });
    },
    /** 站点 */
    getList() {
      this.loading = true;
      listchargeStation(this.queryParams).then((response) => {
        this.vinList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        stationId: null,
        stationName: null,
        equipmentCode: null,
        pipeNum: null,
        listName: null,
        sendTime: null,
        lastedUpdateTime: null,
        whiteListStatus: null,
        sendType: null,
        whiteId: null,
        maxVinNumber: null,
      };
      this.issuingActive = 1
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.getListWhite();
      this.reset();
      this.open = true;
      this.title = "添加VIN码白名单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getVin(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改VIN码白名单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.title == '修改VIN码白名单') {
            updateVin(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addVin(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除VIN码白名单编号为"' + ids + '"的数据项？')
        .then(function () {
          return delVin(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "business/vin/export",
        {
          ...this.queryParams,
        },
        `vin_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style scoped lang="scss">
.infoBox {
  display: flex;
  flex-direction: column;
  align-items: center;

  .serachBox {
    margin: 20px 0;

  }
}
</style>
